package com.han.hotelplat.comm.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


public class RequestUtil {

	@SuppressWarnings("unused")
	private final static ThreadLocal<RequestAttributes> currentRequest = new NamedThreadLocal<RequestAttributes>("Request attributes");
	
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
			System.out.println(session.getId());
		} catch (Exception e) {
			
		}
		return session;
	}
	


	
	public static HttpServletRequest getRequest() {
//		WebApplicationContext wac = ContextLoaderListener.getCurrentWebApplicationContext();
		
		/*ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		ShiroHttpServletRequest req = (ShiroHttpServletRequest) attrs.getRequest();
		*/
//		System.out.println(attrs.getRequest());
//		Thread t = Thread.currentThread();
//		ThreadLoca map = t.thread;
		
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		
//		return (HttpServletRequest) currentRequest.get();
		return request;
	}

	public static ShiroHttpServletRequest getShiroHttpServletRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return (ShiroHttpServletRequest) attrs.getRequest();
	}
	
	public static HttpServletResponse getResponse() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return attrs.getResponse();
	}
	
	public static void setSessionAttribute(String key, Object object){
		getSession().setAttribute(key, object);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(String key, Class<T> clazz){
		return (T)getSessionAttribute(key);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttributeOnce(String key, Class<T> clazz){
		T t = (T)getSessionAttribute(key);
		//removeSessionAttribute(key);
		return t;
	}
	
	public static Object getSessionAttribute(String key){
		return getSession().getAttribute(key);
	}
	
	public static Object getSessionAttributeOnce(String key){
		Object value = getSession().getAttribute(key);
		removeSessionAttribute(key);
		return value;
	}
	
	public static void removeSessionAttribute(String key){
		getSession().removeAttribute(key);
	}
	
	public static void setRequestAttribute(String key, Object object){
		getRequest().setAttribute(key, object);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getRequestAttribute(String key, Class<T> clazz){
		return (T)getRequestAttribute(key);
	}
	
	public static Object getRequestAttribute(String key){
		return HttpUtils.getReqParam(getRequest().getQueryString()).get(key);
	}

	public static boolean isAjaxRequest(){
		boolean b = false;
		HttpServletRequest request = getRequest();
		String header = request.getHeader("X-Requested-With");
		if(StringUtils.equalsIgnoreCase(header, "XMLHttpRequest")){
			b = true;
		}
		return b;
	}
	
	
	@SuppressWarnings("unchecked")
	public static <T> T getParameter(String key, Class<T> clazz){
		try {
			Map<String, Object> result = getParameterMap();
			if("".equals(result.get(key))){
				return null;
			}
			return (T) result.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getParameter(HttpServletRequest request, String key, Class<T> clazz){
		try {
			Map<String, Object> result = getParameterMap(request);
			if("".equals(result.get(key))){
				return null;
			}
			return (T) result.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static Map<String, Object> getParameterMap(HttpServletRequest request){
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, String[]> map = request.getParameterMap();
		for (String k : map.keySet()) {
			if (map.get(k).length > 1 || k.indexOf("[]") > -1){
				result.put(k.replace("[]", ""), map.get(k));
			} else {
				result.put(k, map.get(k)[0]);
			}
		}
		return result;
	}
	
	public static Map<String, String> getParameterMapWithString(HttpServletRequest request){
		Map<String, String> result = new HashMap<String, String>();
		Map<String, String[]> map = request.getParameterMap();
		for (String k : map.keySet()) {
				result.put(k, map.get(k)[0]);
		}
		return result;
	}
	
	public static Map<String, Object> getParameterMap(){
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, String[]> map = getRequest().getParameterMap();
		for (String k : map.keySet()) {
			if (map.get(k).length > 1 || k.indexOf("[]") > -1){
				result.put(k.replace("[]", ""), map.get(k));
			} else {
				result.put(k, map.get(k)[0]);
			}
		}
		return result;
	}
	
	public static Object getParameter(HttpServletRequest request ,String key){
		return getParameter(request, key, Object.class);
	}
	
	public static Object getParameter(String key){
		return getParameter(key, Object.class);
	}




	public static String getRequestParamStringWithInputStream(HttpServletRequest request) {
		 String body = "";
	        try {
	            ServletInputStream inputStream = request.getInputStream(); 
	            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
	            while(true){
	                String info = br.readLine();
	                if(info == null){
	                    break;
	                }
	                if(body == null || "".equals(body)){
	                    body = info;
	                }else{
	                    body += info;
	                }
	            }
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }            
	        return body;
	}
}
